package com.beiding.jsonanalyzer.analyze.func.openfunc;

import com.beiding.jsonanalyzer.analyze.func.FuncFactory;
import com.beiding.jsonanalyzer.analyze.func.base.EasyAggFunc;
import com.beiding.jsonanalyzer.analyze.func.base.FuncFactoryAdaptor;

import java.util.List;

/**
 * 最大值
 *
 * @author 丁常磊
 * @date 2022/5/10 15:53
 */

public class Max {

    public static FuncFactory of(Object exp, boolean distinct) {
        return FuncUtils.buildForEasyAgg(new FuncFactoryAdaptor<EasyAggFunc>() {
            @Override
            protected EasyAggFunc newInstance() {
                return new EasyAggFunc() {
                    @Override
                    public Object agg(List<Object> list) {
                        Double max = null;
                        for (Object o : list) {
                            if (o instanceof Number) {
                                if (max == null) {
                                    max = ((Number) o).doubleValue();
                                } else {
                                    double v = ((Number) o).doubleValue();
                                    if (v > max) {
                                        max = v;
                                    }
                                }
                            }
                        }
                        return max;
                    }

                    @Override
                    public String toString() {
                        if (distinct) {
                            return "max(distinct" + core + ")";
                        } else {
                            return "max(" + core + ")";
                        }
                    }
                };
            }
        }, exp, distinct);
    }

    public static FuncFactory of(Object exp) {
        return of(exp, false);
    }

}
